package com.ny.dao.impl;

import com.ny.dao.StudentDao;
import com.ny.entity.Student;
import com.ny.until.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDaoImpl implements StudentDao {
    private DbUtil dbUtil = new DbUtil();

    @Override
    public Student selectStudent(String sname, String spassword) throws SQLException {
        Connection connection = dbUtil.getCon();
        String sql = "select * from students where name =? and password =?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, sname);
        preparedStatement.setString(2, spassword);
        ResultSet resultSet = preparedStatement.executeQuery();
        Student student = new Student();
        if (resultSet.next()) {
            int id = resultSet.getInt("student_id");
            String name = resultSet.getString("name");
            String phone = resultSet.getString("phone");
            String password = resultSet.getString("password");

            student.setStudentId(id);
            student.setName(name);
            student.setPhone(phone);
            student.setPassword(password);
            return student;

        } else {
            return null;
        }
    }

    @Override
    public int insertStudent(Student student) throws SQLException {

        Connection connection = dbUtil.getCon();

        String sql = "INSERT INTO students(name,phone,password) VALUES ( ?, ?, ?);";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, student.getName());
        preparedStatement.setString(2, student.getPhone());
        preparedStatement.setString(3, student.getPassword());
        int i = preparedStatement.executeUpdate();
        return i;
    }
}